<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/29
 * Time: 14:12
 */

namespace zhtfrontend\controllers;

use common\components\extenders\AjaxObject;
use common\components\helpers\Util;
use common\components\helpers\Fun;
use common\models\datas\Cate;
use common\models\datas\LoginAuth;
use doumiaoduo\buildform\BuildForm;
use EasyWeChat\Message\News;
use yii\helpers\ArrayHelper;
use zhtfrontend\models\datas\Arrangement;
use zhtfrontend\models\datas\ArtRelation;
use zhtfrontend\models\datas\ArtTeaching;
use zhtfrontend\models\datas\ClassLesson;
use zhtfrontend\models\datas\ClassManage;
use zhtfrontend\models\datas\ClassManageAttribute;
use zhtfrontend\models\datas\ClassManageTime;
use zhtfrontend\models\datas\ClassmanageTurn;
use zhtfrontend\models\datas\ClassroomGroup;
use zhtfrontend\models\datas\ClassStudent;
use zhtfrontend\models\datas\Goods;
use zhtfrontend\models\datas\GoodsAttr;
use zhtfrontend\models\datas\GoodsClassTime;
use zhtfrontend\models\datas\Mechanic;
use common\models\datas\Student;
use zhtfrontend\models\datas\OrdersItems;
use zhtfrontend\models\datas\OrdersItemsRelation;
use zhtfrontend\models\datas\StudentCheck;
use zhtfrontend\models\datas\LessonStudent;
use zhtfrontend\models\datas\SubstituteCheck;
use zhtfrontend\models\datas\Teacher;
use yii\data\Pagination;
use yii\web\NotFoundHttpException;
use yii\web\BadRequestHttpException;
use yii\web\Response;
use yii\helpers\Html;
use EasyWeChat\Foundation\Application;

class ArtclassmanageController extends \zhtfrontend\components\bases\BaseController
{
    /**
     * 艺教学班级管理列表
     */
    public function actionIndex()
    {
        $search_data = \Yii::$app->request->get();
        $class_manage = ClassManage::find()->where(['is_old' => 0, 'is_delete' => 0, 'type' => 2])->indexBy('class_id')->orderBy('class_id DESC ');
//        if (!empty($search_data['course'])) {
//            $goods_id1 = Goods::find()->select('id')->where(['like', 'name', $search_data['course']])->column();
//            $class_manage->andWhere(['in', 'associate_id', $goods_id1]);
//        }
//        if (!empty($search_data['teacher'])) {
//            $goods_id2 = GoodsAttr::find()->select('goods_id')->where(['like', 'value', $search_data['teacher']])->andWhere(['obj_type' => 'teacher'])->column();
//            $class_manage->andWhere(['in', 'associate_id', $goods_id2]);
//        }
//        if (!empty($search_data['mechanic'])) {
//            $mechanic_ids = Mechanic::find()->select('id')->where(['like', 'name', $search_data['mechanic']])->column();
//            $class_manage->andWhere(['in', 'mechanic_id', $mechanic_ids]);
//        }
//        if (!empty($search_data['classroom'])) {
//            $goods_id3 = GoodsAttr::find()->select('goods_id')->where(['like', 'value', $search_data['classroom']])->andWhere(['obj_type' => 'classroom_name'])->column();
//            $class_manage->andWhere(['in', 'associate_id', $goods_id3]);
//        }
//        if (!empty($search_data['opentime'])) {
//            $day = floor(\Yii::$app->formatter->asTimestamp($search_data['opentime']) / (60 * 60 * 24));
//            $min = $day * 60 * 60 * 24;
//            $max = ($day + 1) * 60 * 60 * 24;
//            $class_manage->andWhere(['between', 'start_time', $min, $max]);
//        }
//        if (isset($search_data['status']) && $search_data['status'] != null) {
//            $class_manage->andWhere(['status' => $search_data['status']]);
//        }
//        //上课时间
//        if (!empty($search_data['start_time'])) {
//            $goods_id4 = GoodsClassTime::find()->select('goods_id')->where(['start_time' => $search_data['start_time']])->column();
//            $class_manage->andWhere(['in', 'associate_id', $goods_id4]);
//        }
//
//        //老师看属于自己的班级、老师查看自己的班级
//        $role = isset(\Yii::$app->user->identity) ? \Yii::$app->user->identity->role : '';
//        if ($role == 'teache_teacher') {
//            $goods_attr_id4 = GoodsAttr::find()->select('goods_id')->where(['attribute_id' => \Yii::$app->user->identity->teacher_id, 'obj_type' => 'teacher'])->column();
//            $class_manage->andWhere(['in', 'associate_id', $goods_attr_id4])->andwhere(['is_old' => 0]);
//        } elseif ($role == 'class_teacher') {
//            //2017-3-16
//            $teacher = Teacher::find()->select('id')->where(['parent_id' => \Yii::$app->user->identity->id])->column();
//            $teacher = array_push($teacher, \Yii::$app->user->identity->id);
//            $goods_attr_id4 = GoodsAttr::find()->select('goods_id')->where(['in', 'attribute_id', $teacher])->andwhere(['obj_type' => 'teacher'])->column();
//            $class_manage->andWhere(['in', 'associate_id', $goods_attr_id4])->andwhere(['is_old' => 0]);
//        }
        $pages = new Pagination(['totalCount' => $class_manage->count(), 'pageSize' => 10, 'params' => array_merge($_GET, $search_data)]);
        $class_manage = $class_manage->offset($pages->offset)->limit($pages->limit)->all();
        $manageList = Fun::asArray($class_manage, ['arttitle', 'status_name', 'student_count', 'start_day', 'arttime', 'arttitle_type', 'artoperate']);


        return $this->render('index', ['data' => $manageList, 'pages' => $pages]);
    }

    /**
     * 开班
     */
    public function actionOpen()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $model = ClassManage::findOne([$id]);
        if ($model === null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model->scenario = 'art_open';
        $studentCount = ClassStudent::find()->where(['class_manage_id' => $id, 'status' => 0])->count();
        if ($studentCount == 0) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '没有学生暂时不能开班！'));
        }
        $art_teaching = ArtTeaching::findOne(['id' => $model->associate_id]);
        if ($art_teaching === null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        if (\Yii::$app->request->isAjax) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $student = ClassStudent::find()->where(['class_manage_id' => $model->class_id, 'status' => 0])->orderBy('id asc')->all();
            $ajax_object = new AjaxObject();
            $ajax_object->data = count($student) > 0 ? Fun::asArray($student, ['student_name', 'price', 'age', 'tel', 'card_id']) : [];
            return $ajax_object;
        }
        //时间限制
        $class_today = date('w');
        if ($class_today == 0) {
            $class_today = 7;
        }
        if ($class_today != $art_teaching->class_day && $class_today == 7) {
            $start = date('Y/m/d', strtotime(date('Y/m/d')) + ($art_teaching->class_day * (60 * 60 * 24)));
        } elseif ($class_today != $art_teaching->class_day && $class_today < $art_teaching->class_day) {
            $start = date('Y/m/d', strtotime(date('Y/m/d')) + ($art_teaching->class_day - $class_today) * (60 * 60 * 24));
        } elseif ($class_today != $art_teaching->class_day && $class_today > $art_teaching->class_day) {
            $start = date('Y/m/d', strtotime(date('Y/m/d')) + (7 - ($class_today - $art_teaching->class_day)) * (60 * 60 * 24));
        } elseif ($class_today != $art_teaching->class_day && $art_teaching->class_day == 7) {
            $start = date('Y/m/d', strtotime(date('Y/m/d')) + (7 - $class_today) * (60 * 60 * 24));
        } else {
            $start = date('Y/m/d');
        }
        $time_arr = [];
        for ($i = 0; $i < 10; $i++) {
            $time_arr[date('Y/m/d', strtotime($start) + $i * (60 * 60 * 24 * 7))] = date('Y/m/d', strtotime($start) + $i * (60 * 60 * 24 * 7)) . '-' . Fun::getClassDay($art_teaching->class_day);
        }
        $form = new BuildForm('@app/components/forms/artclassmanageForm.php');
        $form->loadModel(['artclassmanage' => $model]);
        $form->setItems('artclassmanage', 'start_time', $time_arr);
        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            if ($model->status == 1) {
                //1、计算class_manage的status、start_time、end_time。
                $start_time = strtotime($model->start_time . ' ' . $art_teaching->star_time);
                $end_time = strtotime(date('Y/m/d', strtotime($model->start_time) + (60 * 60 * 24 * 7) * $art_teaching->class_count));
//                print_r($class_lesson_arr);die;
                $transaction = \Yii::$app->db->beginTransaction();
                try {
                    //2、计算每节课开始结束时间并批量插入class_lesson表。
                    $class_lesson_arr = [];
                    $art_relation = ArtRelation::find()->where(['art_teaching_id' => $art_teaching->id])->orderBy('lesson ASC')->all();
                    foreach ($art_relation as $k => $v) {
                        $class_lesson_arr[$k] = [
                            'class_id' => $id,
                            'class_date' => strtotime($model->start_time) + (60 * 60 * 24 * 7) * $k,
                            'start_time' => str_replace(':', '', $art_teaching->star_time),
                            'end_time' => str_replace(':', '', $art_teaching->end_time),
                            'lesson' => $v->lesson,
                            'title' => isset($v->arrangement->course->name) ? $v->arrangement->course->name : '',
                            'status' => 0,
                            'ovo' => 0,
                            'product_id' => $v->arrangement_id,
                        ];
                    }
                    $model->start_time = $start_time;
                    $model->end_time = $end_time;
                    $model->save(false);
                    Fun::getSiteDb()->createCommand()->batchInsert('{{%class_lesson}}', ['class_id', 'class_date', 'start_time', 'end_time', 'lesson', 'title', 'status', 'ovo', 'product_id'], $class_lesson_arr)->execute();
                    //3、批量修改class_student表status、start_time、end_time字段。
                    Fun::getSiteDb()->createCommand()->update('{{%class_student}}', ['status' => 1, 'start_time' => $start_time, 'end_time' => $end_time], ['class_manage_id' => $id, 'status' => 0])->execute();
                    $transaction->commit();
                    return $this->redirectMessage(\Yii::t('zhtfrontend', '开班成功'), Fun::url(['artclassmanage/index']));
                } catch (\Exception $e) {
                    $transaction->rollBack();
                    return $this->redirectMessage(\Yii::t('zhtfrontend', '开班失败'), Fun::url(['artclassmanage/index']));
                }
            }
        }
        return $this->render('open', ['form' => $form->render(), 'model' => $model]);
    }

    /**
     * 学员列表
     * 代打卡功能
     */
    public function actionDetails()
    {
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $class_manage = ClassManage::findOne($id);
        if ($class_manage === null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $student_list = ClassStudent::find()->where(['class_manage_id' => $class_manage->class_id])->all();

        return $this->render('details', ['details' => $student_list, 'class_id' => \Yii::$app->request->get('id')]);
    }

    /**
     * 调班
     *
     */
    public function actionTransfer()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $model = new ClassmanageTurn();
        $ClassStudent = ClassStudent::findOne($id);
        if ($ClassStudent == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $classManage = ClassManage::findOne($ClassStudent->class_manage_id);
        if ($classManage == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $orderItem = OrdersItems::findOne($ClassStudent->order_sales_id);
        $itemRelation = OrdersItemsRelation::find()->where(['orders_id' => $orderItem->orders_id])->one();
        $class_count = $itemRelation->art_lesson;
        $okCount = 0;
        $lessonIds = ClassLesson::find()->select('lesson_id')->Where(['class_id' => $ClassStudent->class_manage_id])->column();
        if ($ClassStudent->start_time > 0) {
            $okCount = ClassLesson::find()->where(['between', 'class_date', $ClassStudent->start_time, time()])->andWhere(['class_id' => $ClassStudent->class_manage_id])->count();
            $lessonIds = ClassLesson::find()->select('lesson_id')->where(['>', 'class_date', time()])->andWhere(['class_id' => $ClassStudent->class_manage_id])->column();
        }
        $surplusLesson = $class_count - $okCount; //可转课次
        if ($surplusLesson <= 0) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '课已上完不能调了'));
        }
        $art_teaching = ArtTeaching::findOne($classManage->associate_id);
        $inclassList = ArtTeaching::find()->where(['type' => $art_teaching->type, 'status' => 1])->all();
        $arr = [];
        foreach ($inclassList as $k => $v) {
            $class_manage = ClassManage::findOne(['associate_id'=>$v->id]);
            $arr[$class_manage->class_id] = $v->title;
        }

        if (\Yii::$app->request->post('ajax') == 'newclass' && \Yii::$app->request->isAjax) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $class_id = \Yii::$app->request->post('newclass_id');
            $newClass = ClassManage::findOne($class_id);
            if ($newClass->status == 0) {
                return ['status' => 0, 'content' => '此班级未开班需开班后方可操作！', 'lessonList' => []];
            } else {
                $lessonList = ClassLesson::find()->where(['class_id' => $class_id])->andWhere(['>=', 'class_date', time()])->orderBy('lesson ASC')->limit(5)->all();
                return ['status' => 1, 'content' => 'ok！', 'lessonList' => $lessonList];
            }
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $student = Student::findOne($ClassStudent->student_id);
            //class_manage_turn表添加记录
            $model->customer_id = $student->customer_id;
            $model->student_id = $student->id;
            $model->old_class_manage_id = $ClassStudent->class_manage_id;
            $model->admin_id = \Yii::$app->user->id;
            if ($model->save(false)) {
                //修改转班之前的班级学生状态
                $ClassStudent->status = 3;
                $ClassStudent->end_time = time();
                $ClassStudent->save(false);
                //修改转班之前得学生打卡、成长日志表
                StudentCheck::updateAll(['status' => 4, 'created_at' => time()], ['class_student_id' => $ClassStudent->id, 'class_lesson_id' => $lessonIds]); //批量修改签到状态
                LessonStudent::updateAll(['status' => 3, 'check_time' => time()], ['student_id' => $ClassStudent->student_id, 'lesson_id' => $lessonIds]); //批量修改日志状态

                $newClassLesson = ClassLesson::findOne((int)$model->lesson);
                $start_time = $newClassLesson->class_date;


                $newsurplusLessonCount = ClassLesson::find()->where(['class_id' => $model->new_class_manage_id])->andWhere(['>=', 'lesson_id', $model->lesson])->count();
                $orderItem = OrdersItems::findOne($ClassStudent->order_sales_id);
                if ($newsurplusLessonCount < $surplusLesson) {
                    $newaddlesson = $surplusLesson - $newsurplusLessonCount;
                    $newMaxLesson = ClassLesson::find()->where(['class_id' => $model->new_class_manage_id])->orderBy('lesson_id DESC')->one();
                    $new_class_manage = ClassManage::findOne($model->new_class_manage_id);
                    $timeList = ArtTeaching::findOne($new_class_manage->associate_id);
                    $i = 1;
                    $j = 1;
                    while ($j <= $newaddlesson) {
                        $time = $newMaxLesson->class_date + 86400 * $i;
                        $class_today = date('w', $time);
                        if ($class_today == 0) {
                            $class_today = 7;
                        }
                        foreach ($timeList as $t) {
                            if ($t->class_day == $class_today) {
                                $insertLesson[] = [
                                    'class_id' => $newMaxLesson->class_id,
                                    'class_date' => $time,
                                    'start_time' => $newMaxLesson->start_time,
                                    'end_time' => $newMaxLesson->end_time,
                                    'lesson' => $newMaxLesson->lesson + $j,
                                    'title' => $newMaxLesson->title,
                                    'status' => 0,
                                    'ovo' => 1,
                                    'lesson_type' => isset($orderItem->orders->order_type) ? $orderItem->orders->order_type : '',
                                ];
                                $j++;
                            }
                        }
                        $i++;
                    }
                    Fun::getSiteDb()->createCommand()->batchInsert('{{%class_lesson}}', ['class_id', 'class_date', 'start_time', 'end_time', 'lesson', 'title', 'status', 'ovo', 'lesson_type'], $insertLesson)->execute();
                }
                $newClassStudent = new ClassStudent();
                $newClassStudent->class_manage_id = $model->new_class_manage_id;
                $newClassStudent->order_sales_id = $ClassStudent->order_sales_id;
                $newClassStudent->student_id = $ClassStudent->student_id;
                $newClassStudent->status = 1;
                $newClassStudent->start_time = $start_time;
                $newClassStudent->end_time = 0;
                $newClassStudent->is_deposit = 0;
                $newClassStudent->mode = 'A';
                $newClassStudent->save(false);

                //插入签到以及日志
                $lessonList = ClassLesson::find()->where(['class_id' => $model->new_class_manage_id])->andWhere(['>=', 'lesson_id', (int)$model->lesson])->orderBy('lesson_id ASC')->limit($surplusLesson)->all();//获取大于等于次节课的课次
                $z = 1;
                $end_time = 0;
                $insertCheckAttr = [];
                $lesson_students = [];
                foreach ($lessonList as $k => $lesson) {
                    $status = 0;
                    $created_at = 0;
                    if ($lesson->class_date <= time()) {
                        $status = 1;
                        $created_at = time();
                    }
                    $insertCheckAttr[] = [
                        'class_student_id' => $newClassStudent->id,
                        'order_sales_id' => $newClassStudent->order_sales_id,
                        'student_id' => $newClassStudent->student_id,
                        'status' => $status,
                        'created_at' => $created_at,
                        'class_lesson_id' => $lesson->lesson_id,
                        'lesson_type' => $lesson->lesson_type,
                    ];
                    $lesson_students[] = [
                        'lesson_id' => $lesson->lesson_id,
                        'check_time' => $created_at,
                        'student_id' => $newClassStudent->student_id,
                        'status' => $status,
                    ];
                    if ($z == $surplusLesson) {
                        $s = explode(':', Util::getTime($lesson->end_time));
                        $end_time = strtotime(date('Y-m-d', $lesson->class_date)) + (int)$s[0] * 60 * 60 + (int)$s[1] * 60;
                        break;
                    }
                    $z++;
                }
                Fun::getSiteDb()->createCommand()->batchInsert('{{%student_check}}', ['class_student_id', 'order_sales_id', 'student_id', 'status', 'created_at', 'class_lesson_id', 'lesson_type'], $insertCheckAttr)->execute();
                Fun::getSiteDb()->createCommand()->batchInsert('{{%lesson_student}}', ['lesson_id', 'check_time', 'student_id', 'status'], $lesson_students)->execute();

                $newUpdateClassStudent = ClassStudent::findOne($newClassStudent->id);
                $newUpdateClassStudent->end_time = $end_time;
                $newUpdateClassStudent->save(false);
                return $this->redirectMessage(\Yii::t('zhtfrontend', '调班成功'), Fun::url(['artclassmanage/details', 'id' => $classManage->class_id]));

            }
        }
        return $this->render('transfer', ['model' => $model, 'inclassList' => $arr, 'surplusLesson' => $surplusLesson]);
    }

    /**
     * 课时详情
     *
     */
    public function actionLesson()
    {
        $class_id = \Yii::$app->request->get('id');
        if ($class_id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $class_manage = ClassManage::findOne(['class_id' => $class_id]);
        //上课日期
        $class_day = date('Y-m-d', $class_manage->start_time);
        $class_date = [];
        for ($i = 0; $i <= 20; $i++) {
            $class_time = strtotime($class_day) + ($i * 60 * 60 * 24 * 7);
            $class_date[$class_time] = date('Y-m-d', $class_time);
        }
        $teacher = Teacher::find()->where(['is_teaching_art' => 1, 'status' => 1])->all();
        $teacher = ArrayHelper::map($teacher, 'id', 'name');
        $course = [];
        $class_lesson = ClassLesson::findAll(['class_id' => $class_id]);
        $data = [];
        foreach ($class_lesson as $k => $v) {
            $course[$v->product_id] = $v->title;
            $arrangement = Arrangement::findOne($v->product_id);
            $data[$k] = [
                'product_id' => $v->product_id,
                'name' => $v->title,
                'teacher' => $arrangement->teacher->name,
                'teacher_id' => $arrangement->teacher_id,
                'class_day_time' => \Yii::$app->formatter->asDate($v->class_date),
                'class_date' => $v->class_date,
                'class_time' => Fun::getClassTime($v->start_time, $v->end_time),
                'lesson' => $v->lesson,
                'status' => $v->status,
                'lesson_id' => $v->lesson_id,
                'is_overdue' => time() > $v->class_date ? 1 : 0,
            ];
        }
        return $this->render('lesson', ['data' => $data, 'teacher' => $teacher, 'course' => $course, 'class_date' => $class_date]);
    }

    /**
     *
     * 修改艺教学--课程、上课时间、老师
     *
     */
    public function actionUpdatelesson()
    {
        if (\Yii::$app->request->isAjax) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $post = \Yii::$app->request->post();
            $class_lesson = ClassLesson::findOne(['lesson_id' => $post['lesson_id']]);
            $arrangement = Arrangement::findOne($post['course']);
            $class_lesson->class_date = $post['class_date'];
            $class_lesson->product_id = $post['course'];
            $class_lesson->title = $arrangement->course->name;
            if ($class_lesson->save(false)) {
                $arrangement->teacher_id = $post['teacher'];
                if ($arrangement->save(false)) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
    }

    //生成签到

    public function actionGeneratecheck()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        $class_id = \Yii::$app->request->get('class_id');
        if ($id == null || $class_id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $ClassManager = ClassManage::findOne($class_id);
        if ($ClassManager == null || $ClassManager->status == 0) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '班级不存在或者班级未开班'));
        }

        $okLesson = [];
        $okList = ClassLesson::find()->where(['class_id' => $class_id])->andWhere(['<', 'class_date', time()])->orderBy('lesson DESC')->limit(5)->all();
        if ($okList != null) {
            foreach ($okList as $val) {
                $okLesson[$val->lesson_id] = $val->title . '-第' . $val->lesson . '节';
            }
        }
        $lessonList = ClassLesson::find()->where(['class_id' => $class_id])->andWhere(['>=', 'class_date', time()])->orderBy('lesson ASC')->limit(5)->all();
        $lessonLists = [];
        foreach ($lessonList as $val) {
            $lessonLists[$val->lesson_id] = $val->title . '-第' . $val->lesson . '节';
        }
        $lessonLists = $okLesson + $lessonLists;
        if (\Yii::$app->request->post() && \Yii::$app->request->isPost) {
            $post = \Yii::$app->request->post();
            if ($post['lesson_id'] == null) {
                throw new BadRequestHttpException(\Yii::t('zhtfrontend', '数据错误请重试！'));
            }
            $model = ClassStudent::findOne($id);
            $orderItem = OrdersItems::findOne($model->order_sales_id);
            $artModel = ArtTeaching::findOne($ClassManager->associate_id);
            $class_count = $artModel->class_count;
            $orderRelation = OrdersItemsRelation::find()->where(['orders_id' => $orderItem->orders_id])->one();
            if ($orderRelation != null) {
                $class_count = $orderRelation->art_lesson;
            }
            $modelLesson = ClassLesson::findOne((int)$post['lesson_id']);
            $start_time = $modelLesson->class_date;
            $surplusCount = ClassLesson::find()->where(['class_id' => $class_id])->andWhere(['>=', 'lesson_id', (int)$post['lesson_id']])->count();
            $arrangement_ids = ArtRelation::find()->select('arrangement_id')->where(['art_teaching_id' => $artModel->id])->orderBy('lesson ASC')->column();
            $count = count($arrangement_ids);  //总课次

            //此课次后的课次数小于预约课次增加课次
            if ($surplusCount < $class_count) {
                $newLesson = $class_count - $surplusCount;
                $maxLesson = ClassLesson::find()->where(['class_id' => $class_id])->orderBy('lesson_id DESC')->one();
                $Surplusarrangement_ids = ArtRelation::find()->select('arrangement_id')->where(['art_teaching_id' => $artModel->id])->andWhere(['>', 'arrangement_id', $maxLesson->product_id])->orderBy('lesson ASC')->column();
                if (!empty($Surplusarrangement_ids)) {
                    $SurplusarrangementCount = count($Surplusarrangement_ids);
                    if ($SurplusarrangementCount >= $newLesson) {
                        $i = 1;
                        $e = 0;
                        $insertLesson = [];
                        while ($i <= $newLesson) {
                            $row = Arrangement::findOne($Surplusarrangement_ids[$e]);
                            $insertLesson[] = [
                                'class_id' => $maxLesson->class_id,
                                'class_date' => $maxLesson->class_date + 7 * 24 * 60 * 60 * $i,
                                'start_time' => $maxLesson->start_time,
                                'end_time' => $maxLesson->end_time,
                                'lesson' => $maxLesson->lesson + $i,
                                'title' => isset($row->course->name) ? $row->course->name : '',
                                'status' => 0,
                                'ovo' => 1,
                                'product_id' => $Surplusarrangement_ids[$e],
                            ];
                            $i++;
                            $e++;
                        }
                    } else {
                        $insertLesson = [];
                        $i = 1;
                        $x = 0;
                        if ($SurplusarrangementCount > 0) {
                            foreach ($Surplusarrangement_ids as $id) {
                                $row = Arrangement::findOne($id);
                                $insertLesson[] = [
                                    'class_id' => $maxLesson->class_id,
                                    'class_date' => $maxLesson->class_date + 7 * 24 * 60 * 60 * $i,
                                    'start_time' => $maxLesson->start_time,
                                    'end_time' => $maxLesson->end_time,
                                    'lesson' => $maxLesson->lesson + $i,
                                    'title' => isset($row->course->name) ? $row->course->name : '',
                                    'status' => 0,
                                    'ovo' => 1,
                                    'product_id' => $id,
                                ];
                                $i++;
                                $x++;
                            }
                        }
                        $newLessons = $newLesson;
                        if ($x > 0) {
                            $newLessons = $newLesson - $i;
                        }

                        $j = 0;
                        $z = 1;
                        while ($j < $newLessons) {
                            $row = Arrangement::findOne($arrangement_ids[$j]);
                            $insertLesson[] = [
                                'class_id' => $maxLesson->class_id,
                                'class_date' => $maxLesson->class_date + 7 * 24 * 60 * 60 * ($z + $x),
                                'start_time' => $maxLesson->start_time,
                                'end_time' => $maxLesson->end_time,
                                'lesson' => $maxLesson->lesson + $z + $x,
                                'title' => isset($row->course->name) ? $row->course->name : '',
                                'status' => 0,
                                'ovo' => 1,
                                'product_id' => $arrangement_ids[$j],
                            ];
                            $j++;
                            $z++;
                        }
                    }
                    Fun::getSiteDb()->createCommand()->batchInsert('{{%class_lesson}}', ['class_id', 'class_date', 'start_time', 'end_time', 'lesson', 'title', 'status', 'ovo', 'product_id'], $insertLesson)->execute();
                } else {
                    $j = 0;
                    $i = 1;
                    while ($j < $newLesson) {
                        $row = Arrangement::findOne($arrangement_ids[$j]);
                        $insertLesson[] = [
                            'class_id' => $maxLesson->class_id,
                            'class_date' => $maxLesson->class_date + 7 * 24 * 60 * 60 * $i,
                            'start_time' => $maxLesson->start_time,
                            'end_time' => $maxLesson->end_time,
                            'lesson' => $maxLesson->lesson + $i,
                            'title' => isset($row->course->name) ? $row->course->name : '',
                            'status' => 0,
                            'ovo' => 1,
                            'product_id' => $arrangement_ids[$j],
                        ];
                        $j++;
                        $i++;
                    }
                }

                Fun::getSiteDb()->createCommand()->batchInsert('{{%class_lesson}}', ['class_id', 'class_date', 'start_time', 'end_time', 'lesson', 'title', 'status', 'ovo', 'product_id'], $insertLesson)->execute();
            }
            //插入签到以及日志
            $lessonList = ClassLesson::find()->where(['class_id' => $class_id])->andWhere(['>=', 'lesson_id', (int)$post['lesson_id']])->orderBy('lesson_id ASC')->limit($class_count)->all();//获取大于等于次节课的课次
            $z = 0;
            $end_time = 0;
            $insertCheckAttr = [];
            $lesson_students = [];
            foreach ($lessonList as $k => $lesson) {
                $status = 0;
                $created_at = 0;
                if ($lesson->class_date <= time()) {
                    $status = 1;
                    $created_at = time();
                }
                $insertCheckAttr[] = [
                    'class_student_id' => $model->id,
                    'order_sales_id' => $model->order_sales_id,
                    'student_id' => $model->student_id,
                    'status' => $status,
                    'created_at' => $created_at,
                    'class_lesson_id' => $lesson->lesson_id,
                    'lesson_type' => $lesson->lesson_type,
                ];
                $lesson_students[] = [
                    'lesson_id' => $lesson->lesson_id,
                    'check_time' => $created_at,
                    'student_id' => $model->student_id,
                    'status' => $status,
                ];
                $z++;
                if ($z == $class_count) {
                    $s = explode(':', Util::getTime($modelLesson->end_time));
                    $end_time = strtotime(date('Y-m-d', $lesson->class_date)) + (int)$s[0] * 60 * 60 + (int)$s[1] * 60;
                    break;
                }
            }
            $model->status = 1;
            $model->start_time = $start_time;
            $model->end_time = $end_time;
            $model->save(false);

            Fun::getSiteDb()->createCommand()->batchInsert('{{%student_check}}', ['class_student_id', 'order_sales_id', 'student_id', 'status', 'created_at', 'class_lesson_id', 'lesson_type'], $insertCheckAttr)->execute();
            Fun::getSiteDb()->createCommand()->batchInsert('{{%lesson_student}}', ['lesson_id', 'check_time', 'student_id', 'status'], $lesson_students)->execute();

//            $MechanicSubsidy = MechanicSubsidy::find()->where(['class_id'=>$model->class_id,'mechanic_id'=>$model->mechanic_id])->orderBy('lesson ASC')->all();
//            foreach ($MechanicSubsidy as $items){
//                $items->class_date = $lessonList[$items->lesson]['class_date'];
//                $items->save(false);
//            }

            $Student = Student::find()->where(['id' => $model->student_id])->one();
            $auth = LoginAuth::findOne(['user_id' => $Student->customer_id, 'web_site_id' => 17]);
            if ($auth != null) {
                $options = \Yii::$app->params['options_zht'];
                $app = new Application($options);
                $title = '开班通知';
                $name = $artModel->title;
                $date = date('Y-m-d', $model->start_time);
                $time = Util::getWeek($artModel->class_day) . $artModel->star_time . '-' . $artModel->end_time;

                $desc = "课程名称：$name \n 开班日期：$date \n 上课时间：$time";
                $url = \Yii::$app->params['zhtwechat_url'] . '/appointment/index?customer_id=' . $auth->user_id . '&site_id=' . Fun::getSiteId();
                $news = new News([
                    'title' => $title,
                    'description' => $desc,
                    'url' => $url
                ]);
                //$app->staff->message([$news])->to($auth->source_id)->send();
            }

            return $this->redirectMessage(\Yii::t('zhtfrontend', '生成签到成功'), Fun::url(['artclassmanage/details', 'id' => $class_id]));
        }
        return $this->render('generatecheck', ['lessonLists' => $lessonLists]);
    }

    /**
     * 打卡列表
     */
    public function actionSign()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $class_student = ClassStudent::findOne($id);
        $student_check = StudentCheck::find()->where(['student_id' => $class_student->student, 'class_student_id' => $class_student->id])->all();
        $class_lesson_arr = [];
        foreach ($student_check as $k => $v) {
            $class_lesson = ClassLesson::findOne($v->class_lesson_id);
            $class_lesson_arr[$k] = [
                'title' => isset($class_lesson->title) ? $class_lesson->title : '',
                'name' => isset($v->student) ? $v->student->name : '',
                'class_date' => \Yii::$app->formatter->asDate($class_lesson->class_date),
                'end_time' => $class_lesson->end_time,
                'start_time' => $class_lesson->start_time,
                'time' => Fun::getClassTime($class_lesson->start_time, $class_lesson->end_time),
                'lesson' => $class_lesson->lesson,
                'status' => (int)$v->status,
                'lesson_id' => $class_lesson->class_id,
                'student_id' => $v->student_id,
                'class_id' => $class_student->class_manage_id,
                'class_dates' => $class_lesson->class_date,
                'id' => $v->id,
            ];
        }
        return $this->render('sign', ['class_lesson_arr' => $class_lesson_arr]);
    }

    /**
     * 保存打卡
     */
    public function actionSignin()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');

        $student_check = StudentCheck::findOne($id);
        $class_lesson = ClassLesson::findOne($student_check->class_lesson_id);
        $lesson_student = LessonStudent::find()->where(['lesson_id' => $class_lesson->lesson_id, 'student_id' => $student_check->student_id])->one();
        $class_manage = ClassManage::findOne($class_lesson->class_id);
        $art_relation = ArtRelation::findOne(['art_teaching_id' => $class_manage->associate_id, 'lesson' => $class_lesson->lesson]);
        $arrangement = Arrangement::findOne(['id' => $art_relation->arrangement_id]);
        $student = Student::findOne($student_check->student_id);

        $classDate = date('Y-m-d', $class_lesson->class_date);
        $nowDate = date('Y-m-d', time());
        if ($classDate !== $nowDate) {
            $return = ['status' => 2];
            return json_encode($return);
        }
        if ($class_lesson->status == 0) {
            $class_lesson->status = 1;
            $class_lesson->save(false);
        }
        //1、修改student_check表时间、状态
        $student_check->status = 1;
        $student_check->created_at = time();
        if ($student_check->save(false)) {
            //2、修改class_lesson表状态
            $lesson_student->status = 1;
            $lesson_student->check_time = time();
            if ($lesson_student->save(false)) {
                if ($lesson_student->id) {
                    //3、代打卡表substitute_check表插入一条信息
                    $SubstituteCheckModel = new SubstituteCheck();
                    $SubstituteCheckModel->userid = \yii::$app->user->id;
                    $SubstituteCheckModel->student_id = $student_check->student_id;
                    $SubstituteCheckModel->customer_id = $student['customer_id'];
                    $SubstituteCheckModel->created_at = time();
                    if ($SubstituteCheckModel->save(false)) {
                        $str = '';
                        $str .= ' <table>
                         <tr><td colspan="2" align="center">打卡</td></tr>
                         <tr><td>姓名:</td><td>' . Html::encode($student['name']) . '</td></tr>
                         <tr><td>上课日期:</td><td>' . Html::encode(\Yii::$app->formatter->asDate($class_lesson->class_date)) . '</td></tr>
                         <tr><td>课程:</td><td>' . Html::encode($class_lesson->title) . '</td></tr>
                         <tr><td>老师:</td><td>' . Html::encode($arrangement->teacher->name) . '</td></tr>
                         <tr><td>教室:</td><td>' . Html::encode($arrangement->classroom->name) . '</td></tr>
                         <tr><td>开票时间:</td><td>' . date('Y-m-d') . '</td></tr>
                     </table>';
                        $return = ['status' => 1, 'str' => $str];
                        return json_encode($return);
                    }
                } else {
                    $return = ['status' => 0];
                    return json_encode($return);
                }
            }
        }
    }


    /**
     * 修改状态
     */
    public function actionStatus()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('lesson_id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $lesson_id = \Yii::$app->request->get('lesson_id');
        $model = ClassLesson::findOne([$lesson_id]);
        $form = new BuildForm('@app/components/forms/artclasslessonForm.php');
        $form->loadModel(['artclassmanage' => $model]);

        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            $status = \Yii::$app->request->post();
            $class_lesson = ClassLesson::findone([$lesson_id]);
            $class_lesson->status = $status['ClassLesson']['status'];

            if ($class_lesson->save(false)) {
                return $this->redirectMessage(\Yii::t('zhtfrontend', '修改成功'), Fun::url(['artclassmanage/index']));
            } else {
                \Yii::$app->session->setFlash('error', '修改失败');
                return \Yii::$app->response->redirect(Fun::url(['artclassmanage/index']));
            }

        }
        return $this->render('status', ['form' => $form->render(), 'model' => $model]);
    }

    /**
     *  结束课程
     */
    public function actionEndcourse()
    {
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $model = ClassManage::findOne($id);
        if (time() < $model->end_time) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '请在最后一节课结束后结课'));
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $model->status = 2;
            $model->save(false);
            ClassStudent::updateAll(['status' => 2], ['class_manage_id' => $id, 'status' => 1]);
            $transaction->commit();
            return $this->redirectMessage(\Yii::t('zhtfrontend', '操作成功'), Fun::url(['artclassmanage/index']));
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->redirectMessage(\Yii::t('zhtfrontend', '操作失败'), Fun::url(['artclassmanage/index']));
        }
    }

    public function getClassLessonArray($length, $goods_time_array)
    {
        $array = [];
        $ids_length = count($goods_time_array);
        for ($i = 0; $i < $length; $i++) {
            if (empty($array)) {
                $array[] = $goods_time_array[0];
            } else {
                $array[] = $goods_time_array[$i % $ids_length];
            }
        }
        return $array;
    }
}